// 生成签名
import CryptoJS from 'crypto-js'
const VITE_APIKEY = import.meta.env.VITE_APIKEY
const VITE_SECRETKEY = import.meta.env.VITE_SECRETKEY

export const generateSignature = (
  params: any,
  timestamp: any,
  method: any,
  secretKey: string = VITE_SECRETKEY,
) => {
  // 1. 规范化参数
  const normalized = normalizeParams(params, method)
  // 2. 创建待签名消息
  const message = `${timestamp}|${normalized}`

  // 3. 使用 HMAC-SHA256 生成签名
  const signature = CryptoJS.HmacSHA256(message, secretKey)
  // 4. 转换签名为 Base64
  return {
    apiKey: VITE_APIKEY,
    signature: CryptoJS.enc.Base64.stringify(signature),
    timestamp: timestamp,
  }
}

// 参数规范化
const normalizeParams = (params: any, requestMethod: any) => {
  // 过滤敏感参数
  const filtered = Object.keys(params)
    .filter((key) => !['signature', 'timestamp'].includes(key))
    .reduce((obj, key) => {
      obj[key] = params[key] === 0 || params[key] === false || params[key] ? params[key] : ''
      return obj
    }, {})

  // 按键排序
  const sortedKeys = Object.keys(filtered).sort()
  // 构建查询字符串
  return (
    sortedKeys
      .map((key) => {
        // return `${encodeURIComponent(key)}=${encodeURIComponent(filtered[key])}`
        return `${key}=${filtered[key]}`
      })
      .join('&') + `|${requestMethod.toUpperCase()}`
  )
}

// 参数合并
export const separate = (url: string, data: string | AnyObject | ArrayBuffer) => {
  // 手动解析 URL 中的查询参数
  const paramsObject = {}
  const queryString = url.split('?')[1]

  if (queryString) {
    const queryParams = queryString.split('&')
    queryParams.forEach((param) => {
      const [key, value] = param.split('=')
      if (key && value) {
        paramsObject[decodeURIComponent(key)] = decodeURIComponent(value)
      }
    })
  }

  // 确保 data 是一个对象，然后合并 URL 参数与 data
  const newData = {
    ...(typeof data === 'object' && data !== null ? data : {}),
    ...paramsObject,
  }

  // 返回合并后的数据
  return newData
}
